using System;
using System.Data;
using System.Diagnostics;
using System.Xml;
using System.ComponentModel;
using System.Collections;
using System.IO;


using CStock;
using CUtil;
using CIndicators;



//problem
//the path var.is not set after deserialization !

//TODO
//Value_Total is not reflecting the current value of the portfolio (Because it would mean an update - and reading 
//of all share data at start
//to update - call Value_TotalUpdate
namespace CStock
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable"), System.Xml.Serialization.XmlRoot()]
    public class Portfolio : StockObjectBase, IPortfolio, IComparable
    {
        #region fields

        //private string nameUpdate;
        private string ownerID;
        private double value_Initial;
        private string symbol;
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public const string defaultPortfolioName = "DefaultPortfolio";

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        protected DataTable dataTable;

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        protected System.Data.DataSet dataSet;


        [System.Xml.Serialization.XmlIgnoreAttribute()]
        protected string shortFileName;

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        protected IDataItems dataItems;

        private ArrayList tradeEvents;

        private double value_Total;

        private double transferredMoney;

        private double money;


        private double performance;

        //private double relativePerformance;

        private bool writeProtect;

        private double value_Shares;

        

        private IDataItem dataItem_selected;
      
        private ITradeStep tradeStepPortfolio;
        private double value_Bonds;
        private string url_excelSheet;
        private string url_overview;
        string uRL_excelSheet_CommaSeparator;
        //private const int numberOfParameters = 12;
        //private const int numberOfCalculations = 3;

        private bool fetchIntradayQuotes;
        private bool fetchDailyQuotes;
        private bool tradeSimulationPortfolio;
        
        private bool stockTypePortfolio;


        #endregion

        #region constructor

        /// <summary>
        /// beware: Convention: Name shoould be like Edgar_Portfolio1 (trader owner = before _)
        /// </summary>
        public Portfolio()
        {

            ResetPathFromConfiguration();

            this.dataItems = new CStock.DataItems();
            this.tradeEvents = new ArrayList();

           
            tradeStepPortfolio = new TradeStep(this);
            tradeStepPortfolio.Init(false, TradeMoneyType.TradeOneShare, 0f);

            uRL_excelSheet_CommaSeparator = ";";
            this.fetchIntradayQuotes = true;

        }
        public override bool ResetPathFromConfiguration()
        {

            ProgramContext pc = ProgramContext.Instance;
            Debug.Assert(pc != null, "Initialize ProgramContext first ...");
            if (pc != null)
                this.path = pc.Configuration.Directories.PortfolioPath;
            return true;


        }

        public override bool Serialize()
        {
            this.ResetPathFromConfiguration();
            return base.Serialize();
        }
        #endregion

        #region properties

        [Category("Trade_Advanced")]
        public bool TradeSimulationPortfolio
        {
            get
            {
                return tradeSimulationPortfolio;
            }
            set
            {
                tradeSimulationPortfolio = value;
            }
        }
        
        [Category("Trade_Advanced")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool StockType
        {
            get
            {
                return stockTypePortfolio;
            }
            set
            {
                stockTypePortfolio = value;
                this.RaiseObjectChangedEvent(this, "SerializePortfolio", null, value);
            }
        }

        [Browsable(false)]
        public bool StockTypePortfolio
        {
            get
            {
                return stockTypePortfolio;
            }
            set
            {
                stockTypePortfolio = value;
            }
        }
       
        
        
        //public override string Name
        //[Browsable(false)]
        /// <summary>
        /// only for changing the name in the Property Window - when de-serializing, the set is called, which
        /// would mean to serialize the .Name again. Here: do not serialize again
        /// 
        /// !!! beware: Convention: Name shoould be like Edgar_Portfolio1 (trader owner = before _)
        /// </summary>

        [Category("ExchangeData")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public string PortfolioName
        {
            get
            {
                return this.iD;
            }
            set
            {
                //string oldDir = name;
                object oldval = this.iD;
                
                this.iD = value;
                this.iD.Replace(" ", "_");
                this.iD = value;

                string fullFileName = this.path + "\\" + oldval.ToString() + ".Xml";
                System.Diagnostics.Debug.WriteLine("Deleting Portfolio : " + fullFileName);
                File.Delete(fullFileName);

                if (this.iD != null)
                {
                    Serialize();
                }
                this.RaiseObjectChangedEvent(this, "ID", oldval, value);

            }
        }
      
        [Category("2. Performance Advanced")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Cash
        {
            get
            {
                return this.money;
            }

        }
        [Category("2. Performance Advanced"), DisplayName("Value - Current")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Value_Current
        {
            get
            {
                CalculateValue_SharesBonds();
                
                //return ;
                return FormatNumbers.FormatFloatWithTwoDigits(this.value_Shares);

            }
        }
        [Category("1. Quick Overview"),
        DisplayName("-Value Balance")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Value_Balance
        {
            get
            {
                CalculateValue_SharesBonds();
                double d = FormatNumbers.FormatDoubleWithTwoDigits(Convert.ToDouble(this.value_Shares - value_Initial));
                //double f = FormatNumbers.FormatFloatWithTwoDigits(this.value_Shares - value_Initial);
                return d;

            }
        }
        
        [Category("Trade_Advanced"), DisplayName("Value - Balance TradeSimulation")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Value_Balance_TradeSimulation
        {
            get
            {
                
                return FormatNumbers.FormatFloatWithTwoDigits(this.value_Total - value_Initial);

            }
        }



        [Category("2. Performance Advanced"), DisplayName("Value - Initial")]
         [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double Value_Initial
        {
            get
            {
                CalculateValue_Initial();
                return FormatNumbers.FormatFloatWithTwoDigits(this.value_Initial);
                
            }
        }

        [Category("2. Performance Advanced")]
        [Browsable(false)]
        public double Value_Total
        {
            get
            {
                CalculateValue_SharesBonds();
                return FormatNumbers.FormatFloatWithTwoDigits(this.value_Shares);
                //return this.value_Total;
            }
            set
            {
                this.value_Total = value;
            }
        }
        [Browsable(false)]
        public double Value_Bonds
        {
            get
            {
                CalculateValue_SharesBonds();
                return this.value_Bonds;
            }
            
        }
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Browsable(false)]
        public double Value_TotalUpdate
        {
            get
            {
                CalculateValue_SharesBonds();
                return this.value_Total;
            }
            set
            {
                this.value_Total = value;
            }
        }


       
        [Category("Trade_Advanced")]
        [Browsable(false)]
        public bool WriteProtect
        {
            get
            {
                return this.writeProtect;
            }
            set
            {
                this.writeProtect = value;
            }
        }


        
        //save in xml but do not configure it from outside
        [Browsable(false)]
        public double Money
        {
            get
            {
                return this.money;
            }
            set
            {
                this.money = value;
            }
        }



        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public string OwnerID
        {
            get
            {
                return this.ownerID;
            }
             set
            {
                this.ownerID = value;
            }
        }
        [Category("1. Quick Overview"), 
        DisplayName("Performance %")]

        public double Performance
        {
            get
            {
                if (ProgramContext.Instance.Configuration.ProgramMode == ProgramModes.Realtime)
                {
                    if (this.value_Initial == 0)
                        return 0f;
                    if (this.value_Shares == 0)
                        CalculateValue_SharesBonds();
                    if (this.value_Shares == 0)
                        return 0f;
                    if (tradeSimulationPortfolio)
                    {
                        double f = (this.value_Shares - this.value_Initial) * 100 / this.value_Initial;
                        this.performance = FormatNumbers.FormatFloatWithTwoDigits(f);
                    }
                    else
                    {
                        double f = (this.value_Shares - this.value_Initial) * 100 / this.value_Initial;
                        this.performance = FormatNumbers.FormatDoubleWithTwoDigits(Convert.ToDouble(f));
                    }
                }
                else
                {
                    this.performance = this.tradeStepPortfolio.CalculatePerformance();
                    this.performance = FormatNumbers.FormatDoubleWithTwoDigits(performance);

                }
                return this.performance;
            }
         
        }
    
        public override void RaiseObjectChangedEvent(object sender, string propName, object oldVal, object newVal)
        {

            base.RaiseObjectChangedEvent(sender, propName, oldVal, newVal);



        }
        public bool Serialize_DataClasses()
        {
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                //				IDataItem dci = this.dataItems[i];
                //				sum = sum + dci.Number * dci.DataClass.CurrentQuote;
                IDataItem dci = this.dataItems[i];
                Debug.Assert(dci.DataClass.Serialize());

            }
            return true;

        }
        [Category("Trade_Advanced"), DisplayName("Performance Trade Simulation")]
        public double Performance_TradeSimulation
        {
            get
            {
                if (ProgramContext.Instance.Configuration.ProgramMode == ProgramModes.Realtime)
                {
                    if (this.value_Initial == 0)
                        return 0f;
                    if (this.value_Shares == 0)
                        CalculateValue_SharesBonds();
                    if (this.value_Shares == 0)
                        return 0f;
                    double f = (this.value_Total - this.value_Initial) * 100 / this.value_Initial;
                    this.performance = FormatNumbers.FormatFloatWithTwoDigits(f);

                }
                else
                {
                    this.performance = this.tradeStepPortfolio.CalculatePerformance();
                    this.performance = FormatNumbers.FormatDoubleWithTwoDigits(performance);

                }
                return Convert.ToDouble(this.performance);
            }

        }
      
        [Category("Trade_Advanced"), DisplayName("Money - Transferred")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public double TansferedMoney
        {
            get
            {
                return this.transferredMoney;
            }
            set
            {
                object oldVal = this.transferredMoney;
                this.transferredMoney = value;
                this.money = this.money + this.transferredMoney;

                TradeEvent te = new TradeEvent();
                te.Date = ProgramContext.Instance.Configuration.Dates.DateMax;
                te.Money = (double)value;
                te.ShareName = TradeEventEnum.MoneyTransfer.ToString();
                te.ShareID = TradeEventEnum.MoneyTransfer.ToString();
                te.Number = 0;

                this.tradeEvents.Add(te);
                this.RaiseObjectChangedEvent(this, "TransferredMoney", oldVal, value);


            }
        }

    
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public IDataItems DataItems
        {
            get
            {
                return this.dataItems;
            }
            set
            {
                this.dataItems = value;
            }
        }

        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        //used only for serialization and for viewing in the Property grid
        [Browsable(false)]
        public DataItem[] Shares
        {
            get
            {
                try
                {
                    if (this.dataItems.Count > 0)
                    {
                        object[] locObjectArray = this.dataItems.ToArray();
                        int locLength = locObjectArray.Length;
                        DataItem[] locArray = new DataItem[locLength];
                        Array.Copy(locObjectArray, locArray, locLength);
                        return locArray;
                    }
                    else
                        return null;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine("Portfolio - " + "Error creating ItemTypeArray " + exc.Message);
                }
                return null;
            }
            set
            {
                if (this.dataItems == null)
                    this.dataItems = new DataItems();

                this.dataItems.Items.Clear();
                DataItem[] items = value;
                for (int i = 0; i < items.GetLength(0); i++)
                {
                    this.dataItems.Add(items[i], this);

                }
            }
        }
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [Browsable(false)]
        public ArrayList TradeEvents
        {
            get
            {
                return this.tradeEvents;
            }
            set
            {
                this.tradeEvents = value;
            }
        }
        [Category("Web Data")]
        public bool FetchIntradayQuotes  
        {
            get
            {
                return this.fetchIntradayQuotes;
            }
            set
            {
                this.fetchIntradayQuotes = value;
                this.RaiseObjectChangedEvent(this, "FetchIntradayQuotes", fetchIntradayQuotes, value);
                
            }
        }
        [Category("Web Data")]
        public bool FetchDailyQuotes
        {
            get
            {
                return this.fetchDailyQuotes;
            }
            set
            {
                this.fetchDailyQuotes = value;
                this.RaiseObjectChangedEvent(this, "FetchDailyQuotes", fetchDailyQuotes, value);
            }
        }

   

        #endregion

        #region object overrides


        public int CompareTo
            (
            [System.Xml.Serialization.XmlIgnoreAttribute()]
			object obj
            )
        {
            Portfolio objectPortfolio = (Portfolio)obj;
            return this.iD.CompareTo(objectPortfolio.iD);
        }


        public override int GetHashCode()
        {
            return ("Portfolio" + this.Name).GetHashCode();
        }
        #endregion

        #region override XMLSerializable

        public void RenamePortfolioDirectory(string oldName, string newName, string sharePath)
        {
            DirectoryInfo dold = new DirectoryInfo(sharePath + "\\" + oldName);
            DirectoryInfo dnew = new DirectoryInfo(sharePath + "\\" + newName);
            if (dold.Exists)
            {
                if (!dnew.Exists)
                {
                    dnew.Create();
                }
                dold.MoveTo(sharePath + "\\" + newName);
            }




        }
 
        //[Browsable(false)]
        //public string NameUpdate
        //{
        //    get
        //    {
        //        return this.nameUpdate;
        //    }
        //    set
        //    {
        //        //string oldDir = name;
        //        this.nameUpdate = value;
        //        //RenameOldPortfolioDirectory(oldDir);
        //    }
        //}


        #endregion

        #region public methods

    

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MyDataClassN"></param>
        /// <returns></returns>
        public bool RemoveDataClassByID(string MyDataClassN)
        {
            for (int i = 0; i < this.dataItems.Count; i++ )
            {
                IDataItem dc = this.dataItems[i];
                if (dc.DataClass.ID == MyDataClassN)
                {
                    this.dataItems.Remove(dc);
                    this.Serialize();
                    return true;
                }
            }
            return false;

        }

        public bool AddNew(string myPortFileName)
        {
            string strFile = path + myPortFileName + ".xml";
            iD = myPortFileName;
            if (!System.IO.File.Exists(strFile))
            {
                System.IO.File.Create(strFile);
                return true;
            }
            return false;
        }



        public void Refresh()
        {
            CalculateValue_SharesBonds();
            this.value_Total = this.value_Shares + this.money;
        }

        #endregion

        #region implementation


        private void CalculateValue_SharesBonds()
        {
            
            
            this.value_Shares = 0F;
            this.value_Bonds = 0F;
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                //				IDataItem dci = this.dataItems[i];
                //				sum = sum + dci.Number * dci.DataClass.CurrentQuote;
                IDataItem dci = this.dataItems[i];
                if (dci.Number > 0)
                {
                    double fV = dci.Value_Current;
                    value_Shares += fV;
                    if (dci.DataClass.BondType)
                        value_Bonds += fV;

                }
            }
            if (this.tradeSimulationPortfolio)
            {
                this.value_Total = this.value_Shares + this.money;
               
            }
            else
            {
                this.value_Total = this.value_Shares;
            }
            value_Total = FormatNumbers.FormatFloatWithTwoDigits(value_Total);
            value_Bonds = FormatNumbers.FormatFloatWithTwoDigits(value_Bonds);
            value_Shares = FormatNumbers.FormatFloatWithTwoDigits(value_Shares);


           
        }
        private void CalculateValue_Initial()
        {


            this.value_Initial = 0F;
            
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                //				IDataItem dci = this.dataItems[i];
                //				sum = sum + dci.Number * dci.DataClass.CurrentQuote;
                IDataItem dci = this.dataItems[i];
                if (dci.Number > 0)
                {
                    double fV = dci.Value_Initial;
                    value_Initial += fV;
                    

                }
            }

            value_Initial = FormatNumbers.FormatFloatWithTwoDigits(value_Initial);

        }





        #endregion

   
        #region share data

      
        public bool RefreshShareData()
        {
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                IDataClass dc = this.dataItems[i].DataClass;
                object o = (object)dc;
                if (!dc.DeSerialize(ref o))
                    Debug.Assert(false, "Could not read quotes for " + dc.Name);

            }
            this.Serialize();

            return true;
        }


        #endregion

        #region tradings

        public bool ResetTradings()
        {
            //do not reset portfolios with share lists
            if (!this.WriteProtect)
            {

                for (int i = 0; i < this.DataItems.Count; i++)
                {
                    IDataItem dci = this.DataItems[i];
                    dci.Number = 0;
                }
                this.TansferedMoney = 0;
                this.Money = 10000;

                //this.TansferedMoney
                //this.Money = 0;


                this.tradeEvents = new ArrayList();
                this.Serialize();
                return true;


            }
            return false;
        }
        public bool Reset_Empty()
        {
            //do not reset portfolios with share lists
            if (!this.WriteProtect)
            {
                this.tradeEvents = new ArrayList();
                this.DataItems = new DataItems();
                this.Money = 0;

                this.Serialize();
                return true;


            }
            return false;
        }
        public bool TradeShares(IDataItem dci, DateTime myDate, int oldQantity, int newQantity)
        {
            //0. calc. qty and money required:
            int tradedNumber = newQantity - oldQantity;

            IListQuotes qColl = dci.DataClass.QuoteCollection;


            if (qColl == null || qColl.Count < 1 || qColl[myDate] == null)
            {
                return false;
            }
            double shareQuote = qColl[myDate].CLOSEc;
            //dci.BuyDate
            double shareVal = shareQuote;
            double moneyReguired = tradedNumber * shareVal;

            //1. see if we buy or sell:
            if (tradedNumber > oldQantity)
            {
                //2. we buy
                //double shareVal = dci.DataClass.QuoteCollection[this.programContext.Configuration.Dates.DateMax].CLOSEc;
                //the buy date can be different

                //3. See if we have enough money:



                if (moneyReguired > this.Money)
                {
                    //4. cannot buy 'cause I do not have enough money

                    double f = this.Money / shareVal;
                    int qPossible = Convert.ToInt32(System.Math.Round(f));//Convert.ToInt32(this.Money / shareVal);
                    System.Windows.Forms.MessageBox.Show(this.Name + " - You cannot buy " + dci.Number.ToString() + " shares of " + dci.DataClass.Name + " ; \n Cash          :  " + this.Money.ToString() + " ; single price : " + shareVal.ToString() + "\n Try buying maximal : " + qPossible);
                    dci.Number = oldQantity;
                }
                else
                {
                    //5. we have enough money:
                    RaiseTradeEvent(dci, tradedNumber, shareQuote, moneyReguired, myDate);


                }
            }
            else
            {
                //6. we sell:
                RaiseTradeEvent(dci, tradedNumber, shareQuote, moneyReguired, myDate);
            }
            return true;
        }
        private void RaiseTradeEvent(IDataItem dci, int tradedNumber, double buyQuote, double moneyReguired, DateTime myDate)
        {
            //set buy date so that the last buy event is counted //old first buy event is counted
            dci.BuyDate = myDate;
         
            this.Money = this.Money - moneyReguired;
            TradeEvent te = new TradeEvent();

            //raise trade event:
            te.Date = myDate;

            te.Quote = buyQuote;
            te.Money = moneyReguired;
            te.ShareName = dci.DataClass.Name;
            te.ShareID = dci.DataClass.ID;
            te.Number = tradedNumber;
            this.TradeEvents.Add(te);
        }
        #endregion

        #region indicators

        public void ReEvaluates()
        {
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                IDataClass dc = this.dataItems[i].DataClass;
                dc.ReEvaluates();
            }
        }


        #endregion

        #region trading

        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        //used only for serialization and for viewing in lists
        [Browsable(false)]
        public TradeEvent[] Events
        {
            get
            {
                try
                {
                    if (tradeEvents != null && tradeEvents.Count > 0)
                    {
                        object[] arr = this.tradeEvents.ToArray();
                        int length = arr.Length;
                        TradeEvent[] retArr = new TradeEvent[length];
                        Array.Copy(arr, retArr, length);
                        return retArr;
                    }
                    return null;
                }
                catch (Exception exc)
                {
                    Debug.Assert(false, "Portfolio - " + "Error creating ItemTypeArray ", exc.Message);
                }
                return null;
            }
            set
            {
                if (this.tradeEvents == null)
                    this.tradeEvents = new ArrayList();

                this.tradeEvents.Clear();
                TradeEvent[] items = value;
                for (int i = 0; i < items.GetLength(0); i++)
                {
                    this.tradeEvents.Add(items[i]);
                    //items.Add(value[i]);
                }
            }
        }

        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public ITradeStep TradeStepPortfolio
        {
            get
            {
                if (tradeStepPortfolio == null)
                    tradeStepPortfolio = new TradeStep(this);

                return tradeStepPortfolio;
            }
            set
            {
                tradeStepPortfolio = value;
            }
        }

        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public IDataItem DataItem_Selected
        {
            get
            {
                return this.dataItem_selected;


            }
            set
            {
                dataItem_selected = value;
            }
        }
        //[Browsable(false)]
        //[System.Xml.Serialization.XmlIgnoreAttribute()]
        [Category("ExchangeData")]
        public string Symbol
        {
            get
            {
                return this.symbol;


            }
            set
            {
                symbol = value;
            }
        }
        [Category("ExchangeData")]
        [Browsable(false)]
        public string URL_excelSheet_CommaSeparator
        {
            get
            {
                return this.uRL_excelSheet_CommaSeparator;


            }
            set
            {
                uRL_excelSheet_CommaSeparator = value;
            }
        }
        
        [Category("ExchangeData")]
        [Browsable(false)]
        public string URL_excelSheet
        {
            get
            {
                return this.url_excelSheet;


            }
            set
            {
                url_excelSheet = value;
            }
        }
        [Category("ExchangeData")]
        [Browsable(false)]
        public string URL_Overview
        {
            get
            {
                return this.url_overview;


            }
            set
            {
                url_overview = value;
            }
        }
        //private string ;


        #endregion

       
        #region other methods
        public IDataClass GetShareByID(string name)
        {
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                IDataItem di = this.dataItems[i] as DataItem;
                if (di.ID == name)
                {
                    return di.DataClass;
                }

            }
            return null;
        }
        public IDataItem GetDataItemByID(string name)
        {
            for (int i = 0; i < this.dataItems.Count; i++)
            {
                IDataItem di = this.dataItems[i] as DataItem;
                if (di.ID == name)
                {
                    return di;
                }

            }
            return null;
        }

        #endregion

        #region old (unused) data set functionality

        public bool Create_TestData(int numberOfValue_Sharess)
        {


            IDataClassFactory dcf = new DataClassFactory();
            //creates one share 
            //this.money is the portfolio money
            //share value is random
            double valShare = RandomGenerator.Random(5, 400);
            int numberOfShares = Convert.ToInt32(this.money / valShare);

            //for division errors:
            this.money = Convert.ToInt32(numberOfShares * valShare);

            //number of shares is random:


            IDataItem dataItem = dcf.Create_NewDataClass_And_TestData(this.ID, (double)valShare, numberOfValue_Sharess);
            //IDataItem dataItem = dcf.StockObjectBase as IDataItem;
            dataItem.Number = numberOfShares;
            this.DataItems.Items.Add(dataItem);
            this.dataItem_selected = dataItem;

            return true;


        }

        //
        //used for the OLD xml
        //serialization (xml ser. with data sets)
        [Browsable(false)]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public System.Data.DataSet DataSet
        {
            get
            {
                if (dataSet == null)
                    this.dataSet = CreateAndFillDataSet();

                return dataSet;
            }
            set
            {
                dataSet = value;
            }
        }
        private DataSet CreateAndFillDataSet()
        {
            DataSet ds = new DataSet();
            try
            {


                //DataTable table=null;
                if (ds.Tables.Count == 0)
                {
                    ds = CreateDataSet();
                }
                //Use of Portfolio DataSet

                DataTable table = ds.Tables[0];
                //for (int i = 0; i < table.Rows.Count; i++)
                for (int i = 0; i < this.DataItems.Count; i++)
                {
                    IDataItem dataItem = this.DataItems[i];//(this);


                    
                    DataRow row;
                    row = table.NewRow();
                    table.Rows.Add(row);
                    // Then add the new row to the collection.
                    //row["fName"] = "John";
                    //row["lName"] = "Smith";

                    row[0] = dataItem.Name;


                    //for (int j = 0; j < dataItem.NumberOfParameters; j++)
                    //{
                    //    row[j] = dataItem.GetParameterAsObject((short)(j)).Value;
                    //}


                }
                return ds;
            }
            catch (Exception exc)
            {
                Debug.Assert(false, "CreateAndFillDataSet - Error creating dataset ", exc.Message);
                return ds;
            }
        }
        protected DataSet CreateDataSet()
        {
            DataSet dataSet = null;
            dataSet = new DataSet("Portfolio");
            dataSet.Namespace = "NetFrameWork";
            dataTable = new DataTable("Share");
            //IDataClass MyDataClassTemplate = new DataClassDaily();
            IDataItem MyData = new DataItem();

            //for (short j = 0; j < MyData.NumberOfParameters; j++)
            {
                //string str1 = MyData.GetParameterAsObject(j).Name.ToString();
                string str1 = MyData.Name;
                DataColumn dc = new DataColumn(str1);
                //dc.MaxLength = 150;
                dataTable.Columns.Add(dc);
            }

            dataSet.Tables.Add(dataTable);
            return dataSet;
        }

        #endregion


    }
}

